package com.cqsw.bbs.controller;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import okhttp3.*;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.io.IOException;

/**
 * @author: ZackYoung
 * @time: 2020/6/14
 */
@RestController
public class ThirdPartController {
    //    获取歌曲详细信息
    @RequestMapping(value = "ipAttr", produces = "text/html;charset=UTF-8")
    public String ipAttr(String ip)  {
        String url = "http://ip-api.com/json/" + ip + "?lang=zh-CN";
        String ipAttrResult = null;
        try {
            ipAttrResult = interface_jk(url, "get");
        } catch (IOException e) {
            e.printStackTrace();
        }
        StringBuffer sb = new StringBuffer();
        if (ip.equals("127.0.0.1") || ip.equals("0:0:0:0:0:0:0:1")) {
            sb.append("内网");
        } else {
            //需要使用的JSON的parseArray方法，将jsonArray解析为object类型的数组
            JSONObject objects = JSON.parseObject(ipAttrResult);
            if (objects.getString("status").equals("success")) {
                // 获取国家名
                String country = objects.getString("country");
                // 省名
                String regionName = objects.getString("regionName");
                // 城市名
                String city = objects.getString("city");
                // 因特网提供商
                String isp = objects.getString("isp");
                if (isp.equals("Chinanet")) {
                    isp = "电信";
                } else if (isp.equals("China Mobile")) {
                    isp = "移动";
                } else if (isp.contains("China Unicom")) {
                    isp = "联通";
                } else {
                    isp = "";
                }
                // 拼接 格式样式(中国 重庆 重庆)
                sb.append(country + " " + regionName + " " + city + " " + isp);
            }
        }
        //这个方法是去掉stringbuffer的最后一位的字符
//        sb.deleteCharAt(sb.length()-1);
        return sb.toString();
    }

    private String interface_jk(String url, String method) throws IOException {
        OkHttpClient client = new OkHttpClient().newBuilder()
                .build();
        MediaType mediaType = MediaType.parse("text/plain");
        RequestBody body = RequestBody.create(mediaType, "");
        Request request;
        if (method.equals("get")) {
            request = new Request.Builder()
                    .url(url)
                    .addHeader("User-Agent", "Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/83.0.4103.7 Safari/537.36")
                    .get()
                    .build();
        } else {
            request = new Request.Builder()
                    .url(url)
                    .method(method, body)
                    .build();
        }

        Response response = client.newCall(request).execute();
        return response.body().string();
    }
}
